<?php

Zend_Loader::loadClass('Application_Drawable');

abstract class Application_Widget implements Application_Drawable
{
	protected $_view;

	public function __construct()
	{
		// Init view render
		$this->_view = new Zend_View();
		$scriptPath = array (APPLICATION_LIBRARY, 'templates', str_replace('_', DS, str_replace('Application_', '', get_class($this))));
		$this->_view->setScriptPath(implode(DS, $scriptPath));
		$this->_init();
	}

	public function render($viewScript = null)
	{
		if (!is_null($viewScript)) {
			return $this->_view->render($viewScript);
		} else {
			return $this->_view->render('default.phtml');
		}
	}

	protected function _init() {
		$stack = explode("_", strtolower(get_class($this)));
		$layer = "";
		foreach ($stack as $s) {
			$layer .= $s;
			// Javascript
			if (file_exists(PUBLIC_HTML_PATH . DS . 'js' . DS . $layer . DS . 'default.js')) {
				Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view->JQuery()->addJavascriptFile('/js/' . str_replace(DS,'/',$layer) . '/' . 'default.js');
			}
			// Css
			if (file_exists(PUBLIC_HTML_PATH . DS . 'css' . DS . $layer . DS . 'default.css')) {
				Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view->JQuery()->addStylesheet('/css/' . str_replace(DS,'/',$layer) . '/' . 'default.css');
			}
			$layer .= DS;
		}
		// Easy access to request params in view object
		$this->_view->request = Zend_Controller_Front::getInstance()->getRequest()->getParams();
	}

	protected function addJavascript($javascript) {
		if (strpos($javascript, 'http://') === 0)
			Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view->JQuery()->addJavascriptFile($javascript);
		else 
			Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view->JQuery()->addJavascriptFile('/js' . $javascript);
	}

	protected function addStylesheet($css) {
		if (strpos($css, 'http://') === 0)
			Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view->JQuery()->addStylesheet($css);
		else
			Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view->JQuery()->addStylesheet('/css' . $css);
	}

	abstract public function run();
}